<!DOCTYPE html>
<!-- templates/content_review.html -->
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容审核 - AI故事生成器</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href='/static/css/1.css'>
    <link rel="stylesheet" href="/static/css/header.css">
    <link rel="stylesheet" href="/static/css/footer.css">
    <script src="/static/js/header.js" defer></script>
    <style>
        .review-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .section {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        .filters {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .item-card {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background: #fafafa;
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .item-title {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }

        .item-meta {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 10px;
        }

        .item-content {
            background: white;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #4a90e2;
            margin-bottom: 15px;
        }

        .item-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn-approve {
            background: #27ae60;
            color: white;
        }

        .btn-reject {
            background: #e74c3c;
            color: white;
        }

        .btn-delete {
            background: #95a5a6;
            color: white;
        }

        .btn-revert {
            background: #f39c12;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-content {
            background: white;
            width: 400px;
            padding: 20px;
            border-radius: 8px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
        }

        .tab.active {
            border-color: #ddd;
            background: white;
            margin-bottom: -1px;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .violation-badge {
            background: #e74c3c;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            margin-left: 10px;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
{% include 'header.html' %}

<main class="review-container">
    <h1>内容审核</h1>

    <!-- 消息显示 -->
    <div id="message" style="display: none;" class="message"></div>

    <!-- 选项卡 -->
    <div class="tabs">
        <div class="tab active" onclick="switchTab('pending')">待审核</div>
        <div class="tab" onclick="switchTab('reviewed')">已审核</div>
    </div>

    <!-- 待审核内容 -->
    <div id="pending-tab" class="tab-content active">
        <!-- 故事审核部分 -->
        <div class="section">
            <div class="section-header">
                <h2>待审核故事 ({{ pending_story_page.paginator.count }})</h2>
            </div>

            <!-- 故事筛选 -->
            <div class="filters">
                <div class="filter-group">
                    <label>分类:</label>
                    <select id="pending-story-category">
                        <option value="">所有分类</option>
                        {% for category in categories %}
                            <option value="{{ category.id }}" {% if pending_story_category == category.id %}selected{% endif %}>
                                {{ category.name }}
                            </option>
                        {% endfor %}
                    </select>
                </div>

                <div class="filter-group">
                    <label>搜索:</label>
                    <input type="text" id="pending-story-search" value="{{ pending_story_search }}" placeholder="搜索标题、内容或作者">
                    <button onclick="filterPendingStories()" class="btn">搜索</button>
                    <button onclick="clearPendingStoryFilters()" class="btn">清除</button>
                </div>
            </div>

            <!-- 故事列表 -->
            {% if pending_story_page %}
                {% for story in pending_story_page %}
                    <div class="item-card" id="story-{{ story.id }}">
                        <div class="item-header">
                            <div class="item-title">{{ story.title }}</div>
                            <div class="item-meta">
                                作者: {{ story.author.username }} |
                                日期: {{ story.date }} |
                                分类: {% for cat in story.gategory.all %}{{ cat.name }}{% if not forloop.last %}, {% endif %}{% endfor %}
                            </div>
                        </div>

                        <div class="item-content">
                            {{ story.content|truncatewords:50 }}
                            {% if story.content|wordcount > 50 %}
                                <a href="#"
                                   onclick="toggleFullContent('story-full-{{ story.id }}'); return false;">显示全部</a>
                                <div id="story-full-{{ story.id }}" style="display: none;">
                                    {{ story.content }}
                                    <a href="#"
                                       onclick="toggleFullContent('story-full-{{ story.id }}'); return false;">收起</a>
                                </div>
                            {% endif %}
                        </div>

                        <div class="item-actions">
                            <button class="btn btn-approve" onclick="reviewItem('story', {{ story.id }}, 'approve')">通过</button>
                            <button class="btn btn-reject" onclick="showRejectModal('story', {{ story.id }})">拒绝</button>
                            <button class="btn btn-delete" onclick="showDeleteModal('story', {{ story.id }})">删除</button>
                        </div>
                    </div>
                {% endfor %}

                <!-- 分页 -->
                <div class="pagination">
                    {% if pending_story_page.has_previous %}
                        <a href="?pending_story_page={{ pending_story_page.previous_page_number }}{% if pending_story_category %}&pending_story_category={{ pending_story_category }}{% endif %}{% if pending_story_search %}&pending_story_search={{ pending_story_search }}{% endif %}{% if pending_comment_search %}&pending_comment_search={{ pending_comment_search }}{% endif %}{% if pending_comment_page %}&pending_comment_page={{ pending_comment_page.number }}{% endif %}&tab=pending"
                           class="btn">上一页</a>
                    {% endif %}

                    <span>第 {{ pending_story_page.number }} 页，共 {{ pending_story_page.paginator.num_pages }} 页</span>

                    {% if pending_story_page.has_next %}
                        <a href="?pending_story_page={{ pending_story_page.next_page_number }}{% if pending_story_category %}&pending_story_category={{ pending_story_category }}{% endif %}{% if pending_story_search %}&pending_story_search={{ pending_story_search }}{% endif %}{% if pending_comment_search %}&pending_comment_search={{ pending_comment_search }}{% endif %}{% if pending_comment_page %}&pending_comment_page={{ pending_comment_page.number }}{% endif %}&tab=pending"
                           class="btn">下一页</a>
                    {% endif %}
                </div>
            {% else %}
                <div class="empty-state">
                    <p>暂无待审核的故事</p>
                </div>
            {% endif %}
        </div>

        <!-- 评论审核部分 -->
        <div class="section">
            <div class="section-header">
                <h2>待审核评论 ({{ pending_comment_page.paginator.count }})</h2>
            </div>

            <!-- 评论筛选 -->
            <div class="filters">
                <div class="filter-group">
                    <label>搜索:</label>
                    <input type="text" id="pending-comment-search" value="{{ pending_comment_search }}"
                           placeholder="搜索评论内容、用户或故事">
                    <button onclick="filterPendingComments()" class="btn">搜索</button>
                    <button onclick="clearPendingCommentFilters()" class="btn">清除</button>
                </div>
            </div>

            <!-- 评论列表 -->
            {% if pending_comment_page %}
                {% for comment in pending_comment_page %}
                    <div class="item-card" id="comment-{{ comment.id }}">
                        <div class="item-header">
                            <div class="item-title">评论于: {{ comment.store.title }}</div>
                            <div class="item-meta">
                                用户: {{ comment.user.username }} |
                                日期: {{ comment.date|default:"未知" }}
                            </div>
                        </div>

                        <div class="item-content">
                            {{ comment.content }}
                        </div>

                        <div class="item-actions">
                            <button class="btn btn-approve" onclick="reviewItem('comment', {{ comment.id }}, 'approve')">通过</button>
                            <button class="btn btn-reject" onclick="showRejectModal('comment', {{ comment.id }})">拒绝</button>
                            <button class="btn btn-delete" onclick="showDeleteModal('comment', {{ comment.id }})">删除</button>
                        </div>
                    </div>
                {% endfor %}

                <!-- 分页 -->
                <div class="pagination">
                    {% if pending_comment_page.has_previous %}
                        <a href="?pending_comment_page={{ pending_comment_page.previous_page_number }}{% if pending_story_category %}&pending_story_category={{ pending_story_category }}{% endif %}{% if pending_story_search %}&pending_story_search={{ pending_story_search }}{% endif %}{% if pending_comment_search %}&pending_comment_search={{ pending_comment_search }}{% endif %}{% if pending_story_page %}&pending_story_page={{ pending_story_page.number }}{% endif %}&tab=pending"
                           class="btn">上一页</a>
                    {% endif %}

                    <span>第 {{ pending_comment_page.number }} 页，共 {{ pending_comment_page.paginator.num_pages }} 页</span>

                    {% if pending_comment_page.has_next %}
                        <a href="?pending_comment_page={{ pending_comment_page.next_page_number }}{% if pending_story_category %}&pending_story_category={{ pending_story_category }}{% endif %}{% if pending_story_search %}&pending_story_search={{ pending_story_search }}{% endif %}{% if pending_comment_search %}&pending_comment_search={{ pending_comment_search }}{% endif %}{% if pending_story_page %}&pending_story_page={{ pending_story_page.number }}{% endif %}&tab=pending"
                           class="btn">下一页</a>
                    {% endif %}
                </div>
            {% else %}
                <div class="empty-state">
                    <p>暂无待审核的评论</p>
                </div>
            {% endif %}
        </div>
    </div>

    <!-- 已审核内容 -->
    <div id="reviewed-tab" class="tab-content">
        <!-- 已审核故事部分 -->
        <div class="section">
            <div class="section-header">
                <h2>已审核故事 ({{ reviewed_story_page.paginator.count }})</h2>
            </div>

            <!-- 故事筛选 -->
            <div class="filters">
                <div class="filter-group">
                    <label>分类:</label>
                    <select id="reviewed-story-category">
                        <option value="">所有分类</option>
                        {% for category in categories %}
                            <option value="{{ category.id }}" {% if reviewed_story_category == category.id %}selected{% endif %}>
                                {{ category.name }}
                            </option>
                        {% endfor %}
                    </select>
                </div>

                <div class="filter-group">
                    <label>违规状态:</label>
                    <select id="reviewed-story-violation">
                        <option value="">全部</option>
                        <option value="violation" {% if reviewed_story_violation == "violation" %}selected{% endif %}>违规</option>
                        <option value="normal" {% if reviewed_story_violation == "normal" %}selected{% endif %}>正常</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label>搜索:</label>
                    <input type="text" id="reviewed-story-search" value="{{ reviewed_story_search }}" placeholder="搜索标题、内容或作者">
                    <button onclick="filterReviewedStories()" class="btn">搜索</button>
                    <button onclick="clearReviewedStoryFilters()" class="btn">清除</button>
                </div>
            </div>

            <!-- 故事列表 -->
            {% if reviewed_story_page %}
                {% for story in reviewed_story_page %}
                    <div class="item-card" id="reviewed-story-{{ story.id }}">
                        <div class="item-header">
                            <div class="item-title">
                                {{ story.title }}
                                {% if story.rules.id != 2 %}<span class="violation-badge">{{ story.rules.name }}</span>{% endif %}
                            </div>
                            <div class="item-meta">
                                作者: {{ story.author.username }} |
                                日期: {{ story.date }} |
                                分类: {% for cat in story.gategory.all %}{{ cat.name }}{% if not forloop.last %}, {% endif %}{% endfor %}
                            </div>
                        </div>

                        <div class="item-content">
                            {{ story.content|truncatewords:50 }}
                            {% if story.content|wordcount > 50 %}
                                <a href="#"
                                   onclick="toggleFullContent('reviewed-story-full-{{ story.id }}'); return false;">显示全部</a>
                                <div id="reviewed-story-full-{{ story.id }}" style="display: none;">
                                    {{ story.content }}
                                    <a href="#"
                                       onclick="toggleFullContent('reviewed-story-full-{{ story.id }}'); return false;">收起</a>
                                </div>
                            {% endif %}
                        </div>

                        <div class="item-actions">
                            {% if story.rules.id == 2 %}
                                <button class="btn btn-reject" onclick="showRejectModal('story', {{ story.id }})">标记违规</button>
                            {% else %}
                                <button class="btn btn-approve" onclick="removeViolation('story', {{ story.id }})">取消违规</button>
                            {% endif %}
                            <button class="btn btn-revert" onclick="reviewItem('story', {{ story.id }}, 'revert')">撤回审核</button>
                            <button class="btn btn-delete" onclick="showDeleteModal('story', {{ story.id }})">删除</button>
                        </div>
                    </div>
                {% endfor %}

                <!-- 分页 -->
                <div class="pagination">
                    {% if reviewed_story_page.has_previous %}
                        <a href="?reviewed_story_page={{ reviewed_story_page.previous_page_number }}{% if reviewed_story_category %}&reviewed_story_category={{ reviewed_story_category }}{% endif %}{% if reviewed_story_violation %}&reviewed_story_violation={{ reviewed_story_violation }}{% endif %}{% if reviewed_story_search %}&reviewed_story_search={{ reviewed_story_search }}{% endif %}{% if reviewed_comment_search %}&reviewed_comment_search={{ reviewed_comment_search }}{% endif %}{% if reviewed_comment_page %}&reviewed_comment_page={{ reviewed_comment_page.number }}{% endif %}&tab=reviewed"
                           class="btn">上一页</a>
                    {% endif %}

                    <span>第 {{ reviewed_story_page.number }} 页，共 {{ reviewed_story_page.paginator.num_pages }} 页</span>

                    {% if reviewed_story_page.has_next %}
                        <a href="?reviewed_story_page={{ reviewed_story_page.next_page_number }}{% if reviewed_story_category %}&reviewed_story_category={{ reviewed_story_category }}{% endif %}{% if reviewed_story_violation %}&reviewed_story_violation={{ reviewed_story_violation }}{% endif %}{% if reviewed_story_search %}&reviewed_story_search={{ reviewed_story_search }}{% endif %}{% if reviewed_comment_search %}&reviewed_comment_search={{ reviewed_comment_search }}{% endif %}{% if reviewed_comment_page %}&reviewed_comment_page={{ reviewed_comment_page.number }}{% endif %}&tab=reviewed"
                           class="btn">下一页</a>
                    {% endif %}
                </div>
            {% else %}
                <div class="empty-state">
                    <p>暂无已审核的故事</p>
                </div>
            {% endif %}
        </div>

        <!-- 已审核评论部分 -->
        <div class="section">
            <div class="section-header">
                <h2>已审核评论 ({{ reviewed_comment_page.paginator.count }})</h2>
            </div>

            <!-- 评论筛选 -->
            <div class="filters">
                <div class="filter-group">
                    <label>违规状态:</label>
                    <select id="reviewed-comment-violation">
                        <option value="">全部</option>
                        <option value="violation" {% if reviewed_comment_violation == "violation" %}selected{% endif %}>违规</option>
                        <option value="normal" {% if reviewed_comment_violation == "normal" %}selected{% endif %}>正常</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label>搜索:</label>
                    <input type="text" id="reviewed-comment-search" value="{{ reviewed_comment_search }}"
                           placeholder="搜索评论内容、用户或故事">
                    <button onclick="filterReviewedComments()" class="btn">搜索</button>
                    <button onclick="clearReviewedCommentFilters()" class="btn">清除</button>
                </div>
            </div>

            <!-- 评论列表 -->
            {% if reviewed_comment_page %}
                {% for comment in reviewed_comment_page %}
                    <div class="item-card" id="reviewed-comment-{{ comment.id }}">
                        <div class="item-header">
                            <div class="item-title">
                                评论于: {{ comment.store.title }}
                                {% if comment.rules.id != 2 %}<span class="violation-badge">{{ comment.rules.name }}</span>{% endif %}
                            </div>
                            <div class="item-meta">
                                用户: {{ comment.user.username }} |
                                日期: {{ comment.date|default:"未知" }}
                            </div>
                        </div>

                        <div class="item-content">
                            {{ comment.content }}
                        </div>

                        <div class="item-actions">
                            {% if comment.rules.id == 2 %}
                                <button class="btn btn-reject" onclick="showRejectModal('comment', {{ comment.id }})">标记违规</button>
                            {% else %}
                                <button class="btn btn-approve" onclick="removeViolation('comment', {{ comment.id }})">取消违规</button>
                            {% endif %}
                            <button class="btn btn-revert" onclick="reviewItem('comment', {{ comment.id }}, 'revert')">撤回审核</button>
                            <button class="btn btn-delete" onclick="showDeleteModal('comment', {{ comment.id }})">删除</button>
                        </div>
                    </div>
                {% endfor %}

                <!-- 分页 -->
                <div class="pagination">
                    {% if reviewed_comment_page.has_previous %}
                        <a href="?reviewed_comment_page={{ reviewed_comment_page.previous_page_number }}{% if reviewed_story_category %}&reviewed_story_category={{ reviewed_story_category }}{% endif %}{% if reviewed_story_violation %}&reviewed_story_violation={{ reviewed_story_violation }}{% endif %}{% if reviewed_story_search %}&reviewed_story_search={{ reviewed_story_search }}{% endif %}{% if reviewed_comment_violation %}&reviewed_comment_violation={{ reviewed_comment_violation }}{% endif %}{% if reviewed_comment_search %}&reviewed_comment_search={{ reviewed_comment_search }}{% endif %}{% if reviewed_story_page %}&reviewed_story_page={{ reviewed_story_page.number }}{% endif %}&tab=reviewed"
                           class="btn">上一页</a>
                    {% endif %}

                    <span>第 {{ reviewed_comment_page.number }} 页，共 {{ reviewed_comment_page.paginator.num_pages }} 页</span>

                    {% if reviewed_comment_page.has_next %}
                        <a href="?reviewed_comment_page={{ reviewed_comment_page.next_page_number }}{% if reviewed_story_category %}&reviewed_story_category={{ reviewed_story_category }}{% endif %}{% if reviewed_story_violation %}&reviewed_story_violation={{ reviewed_story_violation }}{% endif %}{% if reviewed_story_search %}&reviewed_story_search={{ reviewed_story_search }}{% endif %}{% if reviewed_comment_violation %}&reviewed_comment_violation={{ reviewed_comment_violation }}{% endif %}{% if reviewed_comment_search %}&reviewed_comment_search={{ reviewed_comment_search }}{% endif %}{% if reviewed_story_page %}&reviewed_story_page={{ reviewed_story_page.number }}{% endif %}&tab=reviewed"
                           class="btn">下一页</a>
                    {% endif %}
                </div>
            {% else %}
                <div class="empty-state">
                    <p>暂无已审核的评论</p>
                </div>
            {% endif %}
        </div>
    </div>
</main>

<!-- 拒绝模态框 -->
<div id="reject-modal" class="modal">
    <div class="modal-content">
        <h3>选择违规类型</h3>
        <select id="reject-rule">
            {% for rule in rules %}
                <option value="{{ rule.id }}">{{ rule.name }}</option>
            {% endfor %}
        </select>
        <div style="margin-top: 20px; text-align: right;">
            <button class="btn" onclick="hideModal('reject-modal')">取消</button>
            <button class="btn btn-reject" onclick="submitReject()">确认拒绝</button>
        </div>
    </div>
</div>

<!-- 删除模态框 -->
<div id="delete-modal" class="modal">
    <div class="modal-content">
        <h3>确认删除</h3>
        <p>请选择违规类型（可选）:</p>
        <select id="delete-rule">
            <option value="">无违规类型</option>
            {% for rule in rules %}
                <option value="{{ rule.id }}">{{ rule.name }}</option>
            {% endfor %}
        </select>
        <div style="margin-top: 20px; text-align: right;">
            <button class="btn" onclick="hideModal('delete-modal')">取消</button>
            <button class="btn btn-delete" onclick="submitDelete()">确认删除</button>
        </div>
    </div>
</div>

<!-- 页脚 -->
{% include 'footer.html' %}

<script>
  // 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否需要刷新
    const needRefresh = sessionStorage.getItem('needRefresh');
    const refreshTab = sessionStorage.getItem('refreshTab');

    if (needRefresh === 'true' && refreshTab) {
        // 清除标记
        sessionStorage.removeItem('needRefresh');
        sessionStorage.removeItem('refreshTab');

        // 自动切换到需要刷新的选项卡
        switchTab(refreshTab, true);
    } else {
        // 检查URL参数，激活相应的选项卡
        const urlParams = new URLSearchParams(window.location.search);
        const tab = urlParams.get('tab');
        if (tab === 'reviewed') {
            switchTab('reviewed', false);
        } else {
            switchTab('pending', false);
        }
    }
});

// 切换选项卡
function switchTab(tabName, shouldRefresh = false) {
    // 更新选项卡UI
    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });

    if (tabName === 'pending') {
        document.querySelector('.tab:nth-child(1)').classList.add('active');
        document.getElementById('pending-tab').classList.add('active');

        // 只有在需要时才刷新
        if (shouldRefresh) {
            refreshPendingContent();
        }

        // 更新URL参数
        const url = new URL(window.location);
        url.searchParams.set('tab', 'pending');
        window.history.replaceState({}, '', url);
    } else {
        document.querySelector('.tab:nth-child(2)').classList.add('active');
        document.getElementById('reviewed-tab').classList.add('active');

        // 只有在需要时才刷新
        if (shouldRefresh) {
            refreshReviewedContent();
        }

        // 更新URL参数
        const url = new URL(window.location);
        url.searchParams.set('tab', 'reviewed');
        window.history.replaceState({}, '', url);
    }
}

// 刷新待审核内容
function refreshPendingContent() {
    // 获取当前的筛选参数
    const category = document.getElementById('pending-story-category')?.value || '';
    const storySearch = document.getElementById('pending-story-search')?.value || '';
    const commentSearch = document.getElementById('pending-comment-search')?.value || '';

    // 构建刷新URL
    let url = '?tab=pending';
    if (category) url += `&pending_story_category=${category}`;
    if (storySearch) url += `&pending_story_search=${encodeURIComponent(storySearch)}`;
    if (commentSearch) url += `&pending_comment_search=${encodeURIComponent(commentSearch)}`;

    // 重新加载页面但保持筛选条件
    window.location.href = url;
}

// 刷新已审核内容
function refreshReviewedContent() {
    // 获取当前的筛选参数
    const category = document.getElementById('reviewed-story-category')?.value || '';
    const storyViolation = document.getElementById('reviewed-story-violation')?.value || '';
    const storySearch = document.getElementById('reviewed-story-search')?.value || '';
    const commentViolation = document.getElementById('reviewed-comment-violation')?.value || '';
    const commentSearch = document.getElementById('reviewed-comment-search')?.value || '';

    // 构建刷新URL
    let url = '?tab=reviewed';
    if (category) url += `&reviewed_story_category=${category}`;
    if (storyViolation) url += `&reviewed_story_violation=${storyViolation}`;
    if (storySearch) url += `&reviewed_story_search=${encodeURIComponent(storySearch)}`;
    if (commentViolation) url += `&reviewed_comment_violation=${commentViolation}`;
    if (commentSearch) url += `&reviewed_comment_search=${encodeURIComponent(commentSearch)}`;

    // 重新加载页面但保持筛选条件
    window.location.href = url;
}

// 显示消息
function showMessage(text, type) {
    const messageDiv = document.getElementById('message');
    messageDiv.textContent = text;
    messageDiv.style.display = 'block';
    messageDiv.className = type === 'error' ? 'error-message' : 'success-message';

    setTimeout(() => {
        messageDiv.style.display = 'none';
    }, 3000);
}

// 切换完整内容显示
function toggleFullContent(elementId) {
    const element = document.getElementById(elementId);
    element.style.display = element.style.display === 'none' ? 'block' : 'none';
}

// 显示模态框
function showModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
}

// 隐藏模态框
function hideModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 显示拒绝模态框
function showRejectModal(type, id) {
    currentItemType = type;
    currentItemId = id;
    showModal('reject-modal');
}

// 显示删除模态框
function showDeleteModal(type, id) {
    currentItemType = type;
    currentItemId = id;
    showModal('delete-modal');
}

// 提交审核操作
function reviewItem(type, id, action) {
    const formData = new FormData();
    formData.append('type', type);
    formData.append('id', id);
    formData.append('action', action);

    fetch('{% url "store_system:review_action" %}', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage(data.message, 'success');

                if (action === 'revert') {
                    // 撤回操作，设置需要刷新的标记
                    sessionStorage.setItem('needRefresh', 'true');
                    sessionStorage.setItem('refreshTab', 'pending');

                    // 移除项目
                    const itemElement = document.getElementById(`${type}-${id}`) || document.getElementById(`reviewed-${type}-${id}`);
                    if (itemElement) {
                        itemElement.remove();
                    }

                    // 更新总数显示
                    updateItemCount(type, action);

                    showMessage('撤回成功，切换到待审核选项卡查看最新内容', 'success');
                } else {
                    // 其他操作正常处理
                    const itemElement = document.getElementById(`${type}-${id}`) || document.getElementById(`reviewed-${type}-${id}`);
                    if (itemElement) {
                        itemElement.remove();
                    }
                    updateItemCount(type, action);
                }
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showMessage('操作失败，请重试', 'error');
        });
}

// 更新项目总数
function updateItemCount(type, action) {
    // 获取当前激活的标签页
    const activeTab = document.querySelector('.tab.active');
    if (!activeTab) return;

    const tabText = activeTab.textContent;

    if (tabText === '待审核') {
        // 更新待审核页面的总数
        if (type === 'story') {
            const storyCountElement = document.querySelector('#pending-tab .section:nth-child(1) .section-header h2');
            if (storyCountElement) {
                const match = storyCountElement.textContent.match(/\((\d+)\)/);
                if (match) {
                    const currentCount = parseInt(match[1]);
                    if (action === 'approve' || action === 'reject' || action === 'delete') {
                        storyCountElement.textContent = storyCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount - 1})`
                        );
                    } else if (action === 'revert') {
                        // 从已审核撤回，待审核数量增加
                        storyCountElement.textContent = storyCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount + 1})`
                        );
                    }
                }
            }
        } else if (type === 'comment') {
            const commentCountElement = document.querySelector('#pending-tab .section:nth-child(2) .section-header h2');
            if (commentCountElement) {
                const match = commentCountElement.textContent.match(/\((\d+)\)/);
                if (match) {
                    const currentCount = parseInt(match[1]);
                    if (action === 'approve' || action === 'reject' || action === 'delete') {
                        commentCountElement.textContent = commentCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount - 1})`
                        );
                    } else if (action === 'revert') {
                        // 从已审核撤回，待审核数量增加
                        commentCountElement.textContent = commentCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount + 1})`
                        );
                    }
                }
            }
        }
    } else if (tabText === '已审核') {
        // 更新已审核页面的总数
        if (type === 'story') {
            const storyCountElement = document.querySelector('#reviewed-tab .section:nth-child(1) .section-header h2');
            if (storyCountElement) {
                const match = storyCountElement.textContent.match(/\((\d+)\)/);
                if (match) {
                    const currentCount = parseInt(match[1]);
                    if (action === 'approve' || action === 'reject') {
                        // 从待审核通过或拒绝，已审核数量增加
                        storyCountElement.textContent = storyCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount + 1})`
                        );
                    } else if (action === 'delete' || action === 'revert') {
                        storyCountElement.textContent = storyCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount - 1})`
                        );
                    }
                }
            }
        } else if (type === 'comment') {
            const commentCountElement = document.querySelector('#reviewed-tab .section:nth-child(2) .section-header h2');
            if (commentCountElement) {
                const match = commentCountElement.textContent.match(/\((\d+)\)/);
                if (match) {
                    const currentCount = parseInt(match[1]);
                    if (action === 'approve' || action === 'reject') {
                        // 从待审核通过或拒绝，已审核数量增加
                        commentCountElement.textContent = commentCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount + 1})`
                        );
                    } else if (action === 'delete' || action === 'revert') {
                        commentCountElement.textContent = commentCountElement.textContent.replace(
                            /\(\d+\)/, `(${currentCount - 1})`
                        );
                    }
                }
            }
        }
    }
}

// 提交拒绝操作
function submitReject() {
    const ruleId = document.getElementById('reject-rule').value;

    const formData = new FormData();
    formData.append('type', currentItemType);
    formData.append('id', currentItemId);
    formData.append('action', 'reject');
    formData.append('rule_id', ruleId);

    fetch('{% url "store_system:review_action" %}', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            hideModal('reject-modal');
            if (data.success) {
                showMessage(data.message, 'success');
                const itemElement = document.getElementById(`${currentItemType}-${currentItemId}`) || document.getElementById(`reviewed-${currentItemType}-${currentItemId}`);
                if (itemElement) {
                    itemElement.remove();
                }
                // 更新总数显示
                updateItemCount(currentItemType, 'reject');
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            hideModal('reject-modal');
            console.error('Error:', error);
            showMessage('操作失败，请重试', 'error');
        });
}

// 提交删除操作
function submitDelete() {
    const ruleId = document.getElementById('delete-rule').value;

    const formData = new FormData();
    formData.append('type', currentItemType);
    formData.append('id', currentItemId);
    formData.append('action', 'delete');
    formData.append('rule_id', ruleId);

    fetch('{% url "store_system:review_action" %}', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            hideModal('delete-modal');
            if (data.success) {
                showMessage(data.message, 'success');
                const itemElement = document.getElementById(`${currentItemType}-${currentItemId}`) || document.getElementById(`reviewed-${currentItemType}-${currentItemId}`);
                if (itemElement) {
                    itemElement.remove();
                }
                // 更新总数显示
                updateItemCount(currentItemType, 'delete');
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            hideModal('delete-modal');
            console.error('Error:', error);
            showMessage('操作失败，请重试', 'error');
        });
}

// 移除违规标记操作
function removeViolation(type, id) {
    const formData = new FormData();
    formData.append('type', type);
    formData.append('id', id);
    formData.append('action', 'remove_violation');

    fetch('{% url "store_system:review_action" %}', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage(data.message, 'success');
                // 重新加载页面以更新状态和总数
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showMessage('操作失败，请重试', 'error');
        });
}

// 过滤待审核故事
function filterPendingStories() {
    const category = document.getElementById('pending-story-category').value;
    const search = document.getElementById('pending-story-search').value;

    let url = '?tab=pending';
    if (category) url += `&pending_story_category=${category}`;
    if (search) url += `&pending_story_search=${encodeURIComponent(search)}`;
    if ({% if pending_comment_page.number %}true{% else %}false{% endif %}) url += `&pending_comment_page={{ pending_comment_page.number }}`;
    if ({% if pending_comment_search %}true{% else %}false{% endif %}) url += `&pending_comment_search={{ pending_comment_search }}`;

    window.location.href = url;
}

// 过滤待审核评论
function filterPendingComments() {
    const search = document.getElementById('pending-comment-search').value;

    let url = '?tab=pending';
    if ({% if pending_story_category %}true{% else %}false{% endif %}) url += `&pending_story_category={{ pending_story_category }}`;
    if ({% if pending_story_search %}true{% else %}false{% endif %}) url += `&pending_story_search={{ pending_story_search }}`;
    if (search) url += `&pending_comment_search=${encodeURIComponent(search)}`;
    if ({% if pending_story_page.number %}true{% else %}false{% endif %}) url += `&pending_story_page={{ pending_story_page.number }}`;

    window.location.href = url;
}

// 过滤已审核故事
function filterReviewedStories() {
    const category = document.getElementById('reviewed-story-category').value;
    const violation = document.getElementById('reviewed-story-violation').value;
    const search = document.getElementById('reviewed-story-search').value;

    let url = '?tab=reviewed';
    if (category) url += `&reviewed_story_category=${category}`;
    if (violation) url += `&reviewed_story_violation=${violation}`;
    if (search) url += `&reviewed_story_search=${encodeURIComponent(search)}`;
    if ({% if reviewed_comment_page.number %}true{% else %}false{% endif %}) url += `&reviewed_comment_page={{ reviewed_comment_page.number }}`;
    if ({% if reviewed_comment_violation %}true{% else %}false{% endif %}) url += `&reviewed_comment_violation={{ reviewed_comment_violation }}`;
    if ({% if reviewed_comment_search %}true{% else %}false{% endif %}) url += `&reviewed_comment_search={{ reviewed_comment_search }}`;

    window.location.href = url;
}

// 过滤已审核评论
function filterReviewedComments() {
    const violation = document.getElementById('reviewed-comment-violation').value;
    const search = document.getElementById('reviewed-comment-search').value;

    let url = '?tab=reviewed';
    if (violation) url += `&reviewed_comment_violation=${violation}`;
    if (search) url += `&reviewed_comment_search=${encodeURIComponent(search)}`;
    if ({% if reviewed_story_page.number %}true{% else %}false{% endif %}) url += `&reviewed_story_page={{ reviewed_story_page.number }}`;
    if ({% if reviewed_story_category %}true{% else %}false{% endif %}) url += `&reviewed_story_category={{ reviewed_story_category }}`;
    if ({% if reviewed_story_violation %}true{% else %}false{% endif %}) url += `&reviewed_story_violation={{ reviewed_story_violation }}`;
    if ({% if reviewed_story_search %}true{% else %}false{% endif %}) url += `&reviewed_story_search={{ reviewed_story_search }}`;

    window.location.href = url;
}

// 清除待审核故事筛选
function clearPendingStoryFilters() {
    document.getElementById('pending-story-category').value = '';
    document.getElementById('pending-story-search').value = '';
    filterPendingStories();
}

// 清除待审核评论筛选
function clearPendingCommentFilters() {
    document.getElementById('pending-comment-search').value = '';
    filterPendingComments();
}

// 清除已审核故事筛选
function clearReviewedStoryFilters() {
    document.getElementById('reviewed-story-category').value = '';
    document.getElementById('reviewed-story-violation').value = '';
    document.getElementById('reviewed-story-search').value = '';
    filterReviewedStories();
}

// 清除已审核评论筛选
function clearReviewedCommentFilters() {
    document.getElementById('reviewed-comment-violation').value = '';
    document.getElementById('reviewed-comment-search').value = '';
    filterReviewedComments();
}

// 获取CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
</body>
</html>